import gradio as gr
import random
import time
import json
from llm import llm
# 自定义CSS样式
CSS = """
.gradio-container {
    max-width: 1400px !important; /* 增加最大宽度 */
    padding: 0 20px !important;
}

.tab-content {
    padding: 15px !important;
}

/* 调整主要内容区域布局 */
.row {
    gap: 15px !important; /* 减少行列间距 */
}

/* 调整左右列比例相关样式 */
.column {
    min-width: 0 !important; /* 允许列更灵活地收缩 */
}

/* 聊天区域样式 */
.chatbot-container {
    border-radius: 10px;
    border: 1px solid #e0e0e0;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    width: 100% !important; /* 确保聊天框占满可用宽度 */
}

/* 消息样式 */
.message.user {
    background-color: #f0f7ff !important;
    border: 1px solid #e0e7ff !important;
}

.message.bot {
    background-color: #fafafa !important;
    border: 1px solid #f0f0f0 !important;
}

.message {
    border-radius: 10px !important;
    margin: 8px 0 !important;
    padding: 12px 16px !important;
    max-width: 90% !important; /* 让消息框更宽 */
}

/* 输入区域样式 */
.textbox {
    border-radius: 8px !important;
    border: 1px solid #ddd !important;
    padding: 10px 16px !important;
    width: 100% !important;
}

/* 按钮样式 */
.button {
    border-radius: 8px !important;
    padding: 8px 16px !important;
    transition: all 0.2s ease !important;
    white-space: nowrap !important;
}

.button:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1) !important;
}

.button.primary {
    background-color: #4285f4 !important;
    color: white !important;
    border: none !important;
}

.button.primary:hover {
    background-color: #3367d6 !important;
}

/*  markdown 和卡片样式 */
.markdown-content {
    padding: 16px !important;
    border-radius: 8px !important;
    background-color: #f9f9f9 !important;
    border: 1px solid #eee !important;
    width: 100% !important; /* 确保markdown内容占满列宽 */
    box-sizing: border-box !important;
}

/* 标签页样式 */
.tab-buttons {
    margin-bottom: 15px !important;
}

.tab-button {
    padding: 8px 16px !important;
    border-radius: 6px !important;
    margin-right: 8px !important;
}

/* 文件上传样式 */
.file-upload {
    border-radius: 8px !important;
    border: 2px dashed #ddd !important;
    padding: 20px !important;
    width: 100% !important;
    box-sizing: border-box !important;
}

"""


def random_response(message, history):
    print(message,history)
    # 模拟思考过程
    time.sleep(0.5)
    return random.choice([
        "这个问题很有趣，让我想想...",
        "根据我的理解，答案应该是这样的。",
        "我需要确认一些细节，不过初步来看是这样。",
        "这是一个常见的情况，通常的解决方法是...",
        "让我仔细分析一下，然后给你详细的回答。"
    ])


def clear_history():
    return []


def submit(message, history):
    if not message:  # 防止发送空消息
        return history, ""

    # 追加用户消息
    history.append({"role": "user", "content": message})
    # 获取机器人响应
    bot_response = random_response(message, history)
    history.append({"role": "assistant", "content": ''})

    # 追加机器人响应
    for i in bot_response:
        history[-1]['content'] +=i
    # history.append({"role": "assistant", "content": bot_response})
    # 返回更新后的聊天历史并清空输入框
        time.sleep(0.5)
        yield history, "",'这里返回的是流程'


def load_result_data():
    """从result.json文件加载数据"""
    try:
        with open('result.json', 'r', encoding='utf-8') as f:
            data = json.load(f)
        return data
    except FileNotFoundError:
        # 如果文件不存在，返回默认数据
        return {
            "test_count": 200,
            "success_count": 193,
            "fail_count": 7,
            "avg_steps": 6,
            "max_steps": 12,
            "avg_response_time": 32
        }


def refresh_dashboard():
    """刷新数据看板"""
    data = load_result_data()
    # 构造Markdown内容
    test_count_md = f"""
**测试题目数量**  
# {data['test_count']}
    """
    
    success_count_md = f"""
**成功题目**  
# {data['success_count']}
    """
    
    fail_count_md = f"""
**失败题目**  
# {data['fail_count']}
    """
    
    avg_steps_md = f"""
**平均步骤**  
# {data['avg_steps']}
    """
    
    max_steps_md = f"""
**最高步骤**  
# {data['max_steps']}
    """
    
    avg_response_time_md = f"""
**平均响应时长**  
# {data['avg_response_time']}秒
    """
    
    return [test_count_md, success_count_md, fail_count_md, 
            avg_steps_md, max_steps_md, avg_response_time_md]


with gr.Blocks(css=CSS, title="产品测试平台") as demo:
    gr.Markdown("# 产品测试与管理平台", elem_classes="title")

    with gr.Tab('产品测试', elem_classes="tab-button"):
        with gr.Row():
            # 左侧说明面板
            with gr.Column(scale=1, min_width=250):
                sse_mark_down = gr.Markdown('''
### 测试步骤指南
1. **准备输入**：在输入框中填写测试内容
2. **发送请求**：点击发送按钮或按回车提交
3. **查看结果**：在聊天窗口查看系统响应
4. **分析反馈**：根据回复评估系统表现

可以随时点击"清除所有信息"按钮重置对话历史。
                ''', elem_classes="markdown-content")

            # 右侧聊天区域
            with gr.Column(scale=3):
                chatbot = gr.Chatbot(
                    type="messages",
                    show_copy_button=True,
                    show_label=False,
                    height=500,
                    elem_classes="chatbot-container"
                )

                with gr.Row():
                    user_input = gr.Textbox(
                        placeholder="输入您的消息...",
                        show_label=False,
                        scale=10,
                        elem_classes="textbox"
                    )
                    submit_button = gr.Button(
                        "发送",
                        variant="primary",
                        elem_classes="button primary"
                    )
                    clear_button = gr.Button(
                        "清除",
                        elem_classes="button"
                    )

                # 绑定提交功能
                user_input.submit(submit, [user_input, chatbot], [chatbot, user_input,sse_mark_down])
                submit_button.click(submit, [user_input, chatbot], [chatbot, user_input,sse_mark_down])

                # 绑定清除功能
                clear_button.click(clear_history, None, chatbot)

    with gr.Tab('工具管理', elem_classes="tab-button"):
        gr.Markdown('### 管理正在使用的工具', elem_classes="markdown-content")
        # 工具iframe展示区
        gr.HTML('''
        <div style="margin-top: 15px; border-radius: 8px; border: 1px solid #e0e0e0; overflow: hidden;">
            <iframe src="http://127.0.0.1:5000" width="100%" height="500px" frameborder="0"></iframe>
        </div>
        ''')


    with gr.Tab('题目管理', elem_classes="tab-button"):
        gr.Markdown('### 管理正在使用的示例', elem_classes="markdown-content")

        # 工具iframe展示区
        gr.HTML('''
        <div style="margin-top: 15px; border-radius: 8px; border: 1px solid #e0e0e0; overflow: hidden;">
            <iframe src="http://127.0.0.1:5001" width="100%" height="500px" frameborder="0"></iframe>
        </div>
        ''')

    with gr.Tab('数据看板', elem_classes="tab-button"):
        gr.Markdown("## 测评结果概览", elem_classes="markdown-content")

        # 数据卡片展示
        with gr.Row():
            with gr.Column(scale=1):
                test_count_md = gr.Markdown("""
**测试题目数量**  
# 200
                """, elem_classes="markdown-content")
            with gr.Column(scale=1):
                success_count_md = gr.Markdown("""
**成功题目**  
# 193
                """, elem_classes="markdown-content")
            with gr.Column(scale=1):
                fail_count_md = gr.Markdown("""
**失败题目**  
# 7
                """, elem_classes="markdown-content")

        with gr.Row():
            with gr.Column(scale=1):
                avg_steps_md = gr.Markdown("""
**平均步骤**  
# 6
                """, elem_classes="markdown-content")
            with gr.Column(scale=1):
                max_steps_md = gr.Markdown("""
**最高步骤**  
# 12
                """, elem_classes="markdown-content")
            with gr.Column(scale=1):
                avg_response_time_md = gr.Markdown("""
**平均响应时长**  
# 32秒
                """, elem_classes="markdown-content")

        with gr.Row():
            refresh_btn = gr.Button("刷新数据", elem_classes="button primary")
            refresh_btn.click(
                refresh_dashboard, 
                None, 
                [test_count_md, success_count_md, fail_count_md, 
                 avg_steps_md, max_steps_md, avg_response_time_md]
            )

        # 新测试区域
        gr.Markdown("## 新测试任务", elem_classes="markdown-content")
        with gr.Row():
            test_file = gr.File(label="上传测试文件", elem_classes="file-upload")
            gr.Button("开始测试", elem_classes="button primary")
    with gr.Tab("设置"):
        gr.Markdown('设置key url')
if __name__ == '__main__':
    demo.launch(server_port=9090, debug=True)